package lumis.portal.group.databaseviewmembership.formula;

import static lumis.util.query.IQueryFilter.*;

import java.util.Map;

import lumis.util.query.IQueryFilter;
import lumis.util.query.QueryFilterGroup;
import lumis.util.query.QuerySelect;

/**
 * A formula statement that is composed of two formula statements.
 *
 * @version $Revision: 10458 $ $Date: 2009-06-02 15:49:09 -0300 (Tue, 02 Jun 2009) $
 * @since 4.2.1
 */
class CompoundStatement implements IFormulaStatement
{
	private final IFormulaStatement leftStatement;
	private final String logicalOperator;
	private final IFormulaStatement rightStatement;

	/**
	 * Creates a new compound statement.
	 * @param leftStatement the first statement.
	 * @param logicalOperator the logical operator that will be used
	 * on the statements results.
	 * @param rightStatement the second statement.
	 * @since 4.2.1
	 */
	public CompoundStatement(IFormulaStatement leftStatement, 
			String logicalOperator, IFormulaStatement rightStatement)
	{
		// validate concatenationOperator
		if (!FILTER_CONCATENATION_AND.equals(logicalOperator) &&
				!FILTER_CONCATENATION_OR.equals(logicalOperator))
			throw new IllegalArgumentException("Illegal concatenationOperator: " + logicalOperator);
		
		// set field values
		this.leftStatement = leftStatement;
		this.logicalOperator = logicalOperator;
		this.rightStatement = rightStatement;
	}

	public boolean accept(Map<String, Object> memberData)
	{
		boolean result = leftStatement.accept(memberData);
		
		if (FILTER_CONCATENATION_AND.equals(logicalOperator))
		{
			if (!result)
				return result;
			else
				return rightStatement.accept(memberData);
		}
		else if (FILTER_CONCATENATION_OR.equals(logicalOperator))
		{
			if (result)
				return result;
			else
				return rightStatement.accept(memberData);
		}
		else
		{
			throw new IllegalStateException("Illegal concatenationOperator: " + logicalOperator);
		}
	}

	public IQueryFilter getFilter(QuerySelect select)
	{
		QueryFilterGroup filterGroup = new QueryFilterGroup();

		// add first filter
		filterGroup.addFilter(leftStatement.getFilter(select));
		
		// add seconds filter
		IQueryFilter rightFilter = rightStatement.getFilter(select);
		rightFilter.setFilterConcatenation(logicalOperator);
		filterGroup.addFilter(rightFilter);
		
		return filterGroup;
	}
}
